#!/usr/bin/env python
# -*- coding:utf-8 -*-
from datetime import datetime

from conn.MyLogs import MyLogs
from hcmv.beans.ProjectCamObj import ProjectCamObj


class WebProjectCampService:
    std_array = {}
    conn = None

    def __init__(self, conn):
        self.conn = conn

    def fetch_projects(self, param):
        try:
            count_sql = f" SELECT count(`id`) FROM `mem_projects` WHERE 1=1 %s"
            fetch_sql = f" SELECT `id`,`name`,`camp_sno`, `mems_json`, `update_date`, `create_time` " \
                        f" FROM `mem_projects` WHERE 1=1 %s "
            where_sql = ""
            if len(param['key']) > 0:
                where_sql = where_sql + f" AND CONCAT(`name`,`camp_sno`) like CONCAT('%',\'{param['key']}\','%') "
            int_begin = 0
            if int(param['pageNum']) > 1:
                int_begin = (int(param['pageNum']) - 1) * int(param['pageSize'])
            elif int(param['pageNum']) == 1:
                int_begin = 0 * int(param['pageSize'])
            where_sql_no_limit = where_sql
            where_sql_limit = where_sql_no_limit + f" LIMIT {int_begin}, {int(param['pageSize'])}"
            data_total = self.conn.sql_fetch(count_sql % where_sql_no_limit)
            data_list = self.conn.sql_fetch(fetch_sql % where_sql_limit)
            items = []
            if len(data_list) > 0:
                items = [ProjectCamObj.load_db_2_dict(data=item) for item in data_list]
            return {"code": 200, "data": items, "total": data_total[0][0]}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    def fetch_one(self, id):
        if int(id) == 0:
            return {"code": 200, "data": ProjectCamObj.init_dict()}
        fetch_sql = f" SELECT `id`,`name`,`camp_sno`, `mems_json`, `update_date`, `create_time` " \
                    f" FROM `mem_projects` WHERE 1=1 " \
                    f" AND `id` = \'{id}\'"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                res = [ProjectCamObj.load_db_2_dict(item) for item in items]
                return {"code": 200, "data": res[0]}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def add_project(self, project):
        try:
            insert_sql = f" INSERT INTO `mem_projects` ({ProjectCamObj.to_string(False)}) " \
                         " VALUES ( %s )" % ProjectCamObj.concat_datas(project)
            self.conn.sql_commit(insert_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def update_project(self, project, id):
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        add_check = self.count_one(id=id)
        if not add_check:
            return {"code": 404, "data": None}
        try:
            old_data = self.fetch_one(id=id)
            update_str = ProjectCamObj.split_params(project)
            update_sql = f" UPDATE `mem_projects` SET %s, `update_date`=\'{current_time}\'" \
                         f" WHERE `id`= \'%s\'" % (update_str, id)
            self.conn.sql_commit(update_sql)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}


    def drop_project(self, id):
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        add_check = self.count_one(id=id)
        if not add_check:
            return {"code": 404, "data": None}
        try:
            execute_SQL = f" DELETE FROM `mem_projects` " \
                          f" WHERE `id` = \'{id}\'"
            self.conn.sql_commit(execute_SQL)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def count_one(self, id) -> bool:
        fetch_sql = f"SELECT count(`id`) FROM `mem_projects` WHERE 1 = 1 " \
                    f" AND `id` = \'{id}\'"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                return items[0][0] > 0
            return False
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def fetchMemberTransJson(self, param):
        fetch_sql = f" SELECT `id`,`member_id`,`member_sno`,`weight_json`,`name`,`uname`,`sex`,`STATUS` " \
                    f" FROM `view_member_weight` WHERE 1=1 %s "
        try:
            where_sql = f" AND `STATUS`= \'{param['status']}\'"
            order_sql = where_sql + f" ORDER BY `member_id` DESC"
            data_list = self.conn.sql_fetch(fetch_sql % order_sql)
            items = []
            if len(data_list) > 0:
                items = [{"label": item[4], "key": int(item[0]), "value": item[1]} for item in data_list]
            return {"code": 200, "data": items}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}
